//
//  LHSegMentControl.m
//  lehuotest
//
//  Created by ice on 2017/1/12.
//  Copyright © 2017年 QF. All rights reserved.
//

#import "LHSegMentControl.h"
#import "UIView+Utils.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define Margin 10

@interface LHSegMentControl()<UIScrollViewDelegate>


/**
 存放item的scrollView
 */
@property (nonatomic, strong) UIScrollView *scroller;

@property (nonatomic, strong) UIButton *sortButton;


/**
 存放所有button
 */
@property (nonatomic, strong) NSMutableArray *buttonArray;


/**
 下划线指示器
 */
@property (nonatomic, strong) UIView *indicatorView;

@end

@implementation LHSegMentControl

-(NSMutableArray *)buttonArray
{
    if (!_buttonArray){
        _buttonArray = [NSMutableArray array];
    }
    return _buttonArray;
}
-(UIScrollView *)scroller
{
    if(!_scroller){
        _scroller  = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _scroller.delegate = self;
        _scroller.pagingEnabled = NO;
        _scroller.showsVerticalScrollIndicator = NO;
        _scroller.showsHorizontalScrollIndicator = NO;
        _scroller.backgroundColor = [UIColor clearColor];
    }
    return _scroller;
}
- (UIButton *)sortButton
{
    if (_sortButton == nil) {
        _sortButton = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width-self.frame.size.height, 0, self.frame.size.height, self.frame.size.height)];
        [_sortButton setImage:[UIImage imageNamed:@"ks_home_plus"] forState:UIControlStateNormal];
        _sortButton.backgroundColor = [UIColor whiteColor];
        _sortButton.layer.shadowColor = [UIColor whiteColor].CGColor;
        _sortButton.layer.shadowOpacity = 1;
        _sortButton.layer.shadowRadius = 5;
        _sortButton.layer.shadowOffset = CGSizeMake(-10, 0);
        
        [_sortButton addTarget:self action:@selector(sortButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sortButton;
}
-(instancetype) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = [UIColor whiteColor];
        [self commitUI];
        self.scroller.scrollsToTop = NO;
    }
    return self;
}
-(UIView *)indicatorView
{
    if (!_indicatorView){
        _indicatorView = [[UIView alloc] init];
        _indicatorView.backgroundColor = _indicatorColor;
    }
    return _indicatorView;
}
-(void) commitUI
{
    
    _indicatorViewHeight = 2;
    
    _IsShowIndicatorView = YES;
    
    _textScale = 0.2;
    
    _titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]};
    
    _selectedTitleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blueColor]};
    
    _isShowSortBtn = NO;
    
    _indicatorColor = [UIColor redColor];
    
    [self addSubview:self.scroller];
    
    if (_IsShowIndicatorView){
        [self.scroller addSubview:self.indicatorView];
    }
    
    if (_isShowSortBtn){
        [self addSubview:self.sortButton];
    }
    
}

-(void) setTitles:(NSArray *)titles
{
    _titles = titles;
    CGFloat x = Margin;
    CGFloat margin = Margin;
    
    for (int i = 0 ; i < _titles.count; i++) {
        NSString *title = _titles[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [button setTitle:title forState:UIControlStateNormal];
        
        button.titleLabel.font = self.titleTextAttributes[NSFontAttributeName];

        [button setTitleColor:self.titleTextAttributes[NSForegroundColorAttributeName] forState:UIControlStateNormal];
        
        CGSize size = [title sizeWithAttributes:@{NSFontAttributeName : button.titleLabel.font}];
        button.frame = CGRectMake(x, 0, size.width+margin*2, self.frame.size.height);
        if (i == 0 && self.IsShowIndicatorView){
            self.indicatorView.frame = CGRectMake(button.frame.origin.x, self.frame.size.height-_indicatorViewHeight, button.frame.size.width, _indicatorViewHeight);
        }
        x += button.bounds.size.width;
        button.tag = 10+i;
        [button addTarget:self action:@selector(buttonSelect:) forControlEvents:UIControlEventTouchUpInside];
        [self.scroller addSubview:button];
        [self.buttonArray addObject:button];
        
    }
    [self buttonSelect:self.buttonArray[0]];
    self.scroller.contentSize = CGSizeMake(x + margin + (_isShowSortBtn ? self.sortButton.frame.size.width:0), 0);

}



-(void) setTextScale:(CGFloat)textScale
{
    _textScale = textScale;
}

-(void) setIsShowIndicatorView:(BOOL)IsShowIndicatorView
{
    _IsShowIndicatorView = IsShowIndicatorView;
    self.indicatorView.hidden = !IsShowIndicatorView;
}

-(void) setIndicatorViewHeight:(CGFloat)indicatorViewHeight
{
    _indicatorViewHeight = indicatorViewHeight;
    CGRect rect = self.indicatorView.frame;
    rect.size.height = indicatorViewHeight;
    self.indicatorView.frame = rect;
}
-(void) setIndicatorColor:(UIColor *)indicatorColor
{
    _indicatorColor = indicatorColor;
    self.indicatorView.backgroundColor = indicatorColor;
}
-(void) setIsShowSortBtn:(BOOL)isShowSortBtn
{
    _isShowSortBtn = isShowSortBtn;
    if (isShowSortBtn){
     [self addSubview:self.sortButton];
    }
}

-(void) setTitleTextAttributes:(NSDictionary *)titleTextAttributes
{
    _titleTextAttributes = titleTextAttributes;
}

-(void) setSelectedTitleTextAttributes:(NSDictionary *)selectedTitleTextAttributes
{
    _selectedTitleTextAttributes = selectedTitleTextAttributes;
}

-(void) buttonSelect:(UIButton *)btn
{
    if (self.pageChangeBlock){
        self.pageChangeBlock(btn.tag - 10);
    }
    //改变指示器位置
    [self titleBtnSelected:btn];

}


//重置所有按钮的状态
-(void) reSetAllLabelNormal
{
    for (UIButton *button in self.buttonArray) {
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.transform = CGAffineTransformMakeScale(1,  1);
    }
}

/** 标题选中颜色改变以及指示器位置变化 */
- (void)titleBtnSelectedWithScrollView:(UIScrollView *)scrollView {
    // 1、计算滚动到哪一页
    NSInteger index = scrollView.contentOffset.x / scrollView.frame.size.width;
    // 2、把对应的标题选中
    UIButton *selectedBtn = self.buttonArray[index];
    [self titleBtnSelected:selectedBtn];
}
/** 给外界scrollViewDidScroll方法提供文字渐显效果 */
- (void)titleBtnColorGradualChangeScrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat curPage = scrollView.contentOffset.x / scrollView.bounds.size.width;
    NSLog(@"curPage = %f",curPage);
    // 左边label角标
    NSInteger leftIndex = curPage;
    // 右边的label角标
    NSInteger rightIndex = leftIndex + 1;
    
    // 获取左边的Button
    UIButton *left_btn = self.buttonArray[leftIndex];
      
    // 获取右边的Button
    UIButton *right_btn;
    if (rightIndex <= self.buttonArray.count - 1) {
        right_btn = self.buttonArray[rightIndex];
    }
    
    // 计算下右边缩放比例
    CGFloat rightScale = curPage - leftIndex;
    
    // 计算下左边缩放比例
    CGFloat leftScale = 1 - rightScale;
//    NSLog(@"jigege left%f  right%f",leftScale,rightScale);
    // 左边缩放
    left_btn.transform = CGAffineTransformMakeScale(leftScale * _textScale + 1, leftScale * _textScale + 1);
    // 右边缩放
    right_btn.transform = CGAffineTransformMakeScale(rightScale * _textScale + 1, rightScale * _textScale + 1);
    
    // 设置文字颜色渐变
    left_btn.titleLabel.textColor = [UIColor colorWithRed:0 green:0 blue:leftScale alpha:1];
    right_btn.titleLabel.textColor = [UIColor colorWithRed:0 green:0 blue:rightScale alpha:1];

    //左滑（historyX:begin  scrollView.contentOffset.x:end）
    if (scrollView.contentOffset.x<self.historyX) {

        self.indicatorView.left = right_btn.left + Margin -(right_btn.left - left_btn.left)*leftScale;
        //新宽度
        CGFloat offsetWidth = (right_btn.width-left_btn.width)*leftScale;
        CGFloat newW = right_btn.width-Margin * 2-offsetWidth;
        self.indicatorView.width = newW;

    } else if (scrollView.contentOffset.x>self.historyX) {
        
        if (curPage == self.buttonArray.count-1){
            return;
        }

        self.indicatorView.left = left_btn.left+Margin + (right_btn.left - left_btn.left)*rightScale;
        //新宽度
        CGFloat offsetWidth = (right_btn.width - left_btn.width)*rightScale;
        CGFloat newW = left_btn.width-Margin *2+offsetWidth;
        self.indicatorView.width = newW;
        
    }
    
}


/**
  滚动标题选中居中

 @param centerBtn 选中button
 */
- (void)titleBtnSelectededCenter:(UIButton *)centerBtn {
    // 计算偏移量
    CGFloat offsetX = centerBtn.center.x - self.width * 0.5;
    
    if (offsetX < 0) offsetX = 0;
    
    // 获取最大滚动范围
    CGFloat maxOffsetX = self.scroller.contentSize.width - self.width;
    
    if (offsetX > maxOffsetX) offsetX = maxOffsetX;
    
    // 滚动标题滚动条
    [self.scroller setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

/**
 标题选中颜色改变以及指示器位置变化

 @param button button
 */
- (void)titleBtnSelected:(UIButton *)button {
    [self reSetAllLabelNormal];
    [button setTitleColor:self.selectedTitleTextAttributes[NSForegroundColorAttributeName] forState:UIControlStateNormal];
    button.transform = CGAffineTransformMakeScale(1+self.textScale ,1+self.textScale);
    [UIView animateWithDuration:0.20 animations:^{
        self.indicatorView.width = button.width-Margin * 2;
        self.indicatorView.centerX = button.centerX;

    } completion:^(BOOL finished) {
         [self titleBtnSelectededCenter:button];
    }];

}


-(void) sortButtonClick
{
    
}
-(void) dealloc
{
    self.pageChangeBlock = nil;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
